package br.edu.ufcg.greengrid.workload;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import br.edu.ufcg.greengrid.event.Event;

public class GWAWorkloadParser extends AbstractWorkloadParser {

	private static final String SUBMITTIME = "SubmitTime";

	private static final String RUNTIME = "RunTime";

	public GWAWorkloadParser() {
		try {
			Class.forName("org.sqlite.JDBC");
		} catch (ClassNotFoundException e) {
			throw new RuntimeException("Missing SQLite JDBC library.");
		}
	}

	public void parse(String inputFileName, String outputFileName) throws IOException, SQLException {
		File inputFile = getInputFile(inputFileName);
		File outputFile = getOutputFile(outputFileName);

		parse(inputFile, outputFile);

	}

	public void parse(File inputFile, File outputFile) throws SQLException, IOException {

		String sql = "SELECT " + SUBMITTIME + ", " + RUNTIME + " FROM Jobs ORDER BY " + SUBMITTIME + ";";

		Connection conn = null;
		Statement stat = null;
		ResultSet rs = null;
		BufferedWriter bw = null;

		try {
			conn = DriverManager.getConnection("jdbc:sqlite:" + inputFile.getPath());
			stat = conn.createStatement();
			rs = stat.executeQuery(sql);
			bw = new BufferedWriter(new FileWriter(outputFile));

			while (rs.next()) {
				Long submitTime = rs.getLong(SUBMITTIME);
				Long runtime = rs.getLong(RUNTIME);
				bw.write(submitTime + Event.SEPARATOR + runtime);
				bw.newLine();
			}
		} finally {
			if (rs != null) {
				rs.close();
			}
			if (stat != null) {
				stat.close();
			}
			if (conn != null) {
				conn.close();
			}
			if(bw != null){
				bw.close();
			}
		}
	}

}
